package com.mgy.example.dao.config.db.sharding;

import com.mgy.example.constants.Constant;
import io.shardingsphere.api.algorithm.sharding.ListShardingValue;
import io.shardingsphere.api.algorithm.sharding.ShardingValue;
import io.shardingsphere.api.algorithm.sharding.hint.HintShardingAlgorithm;

import java.util.Collection;
import java.util.Collections;

/**
 * 基于hint的分库策略
 *
 * @author mgy
 */
public class DatabaseHintShardingAlgorithm implements HintShardingAlgorithm {

    /**
     * Sharding.
     *
     * <p>sharding value injected by hint, not in SQL.</p>
     *
     * @param availableTargetNames available data sources or tables's names
     * @param shardingValue        sharding value
     * @return sharding result for data sources or tables's names
     */
    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, ShardingValue shardingValue) {
        for (String each : availableTargetNames) {
            int dbNo = (int) ((ListShardingValue) shardingValue).getValues().iterator().next();
            int eachDbNo = Integer.valueOf(each.substring(each.lastIndexOf(Constant.UNDERLINE) + 1));
            if (eachDbNo == dbNo) {
                return Collections.singletonList(each);
            }
        }
        return null;
    }
}
